global class ProvisioningService {

        public static final string defaultFeed ='https://apps-apis.google.com/a/feeds/myafza.ae/user/2.0'; 

        GoogleService service = new GoogleService('provision');

        public Boolean useClientLogin(String username, String password)
        {
            return service.authenticateWithClientLogin(username, password, 'apps'); 
        }
                        
        public void insertEntryXML ( String body ) {        
            service.makePostRequest(ProvisioningService.defaultFeed , body);             
        }
         
        public HttpResponse response { get { return service.response; } } 
        
        public static void sendMailAlert(Integer statusResponse, String bodymessage, String acnt) {//Send an email to the team support 
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {'porquillo@cloudconceptgroup.com','geo@cloudconceptgroup.com'};
            mail.setToAddresses(toAddresses);
            mail.setSubject('Google Service Provisioning Error: ');
            mail.setPlainTextBody('Google Provisioning error occured with company ' +  acnt  + ' result : ' + statusResponse + '(' + bodymessage + ')');
            Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
        }
       
        
    
    //@future(callout=true)     
    Webservice static String postServiceRequest(Id myId, String fName, String lName, String mob) {
        
        //MyAFZA proccess
        Account getMyName = [SELECT Id, Name, Authorized_Manager_s_Name__c, Authorize_Managers_Mobile_No__c, isRandomPasswordGenerated__c, MyAFZA_Account_ID__c, MyAFZARandomPassword__c, isGoogleProvisioned__c FROM Account WHERE id=: myId];
        //List<Account> updateAccntList = new List<Account>();
        
            String atom;
            //End MyAFZA process
            system.debug('fields retrieved =>' + getMyName);
               
    
            if(getMyName.isGoogleProvisioned__c == false ) {
                                       
                //generate passsword
                String randomStr = PasswordGenerator.getPassword(3);
                if(getMyName.isRandomPasswordGenerated__c == false) {
                    System.debug('Random Password creation fires'); 
                    String firstName = fName.left(1);
                    String lastName = lname.left(1);
                    getMyName.MyAFZARandomPassword__c = firstName + lastName + '123!!!' + randomStr;              
                
                 }
    
                    //encrypt password to sha1
                    Blob hash = Crypto.generateDigest('SHA1', Blob.valueOf(getMyName.MyAFZARandomPassword__c));
                    String encryptedPassword = EncodingUtil.convertToHex(hash);
                    
                    System.debug('Username:' + getMyName.MyAFZA_Account_ID__c + ', Password: ' + encryptedPassword + ', familyName:' + lName + ', GivenName:' + fName);
                   
                    atom = '<?xml version="1.0" encoding="UTF-8"?><atom:entry xmlns:atom="http://www.w3.org/2005/Atom" xmlns:apps="http://schemas.google.com/apps/2006"><atom:category scheme="http://schemas.google.com/g/2005#kind" term="http://schemas.google.com/apps/2006#user"/>'+
                '<apps:login userName="' + getMyName.MyAFZA_Account_ID__c  + '" password="' + encryptedPassword + '" hashFunctionName="SHA-1" suspended="false"/><apps:quota limit="2048"/><apps:name familyName="' + lName +'" givenName="'+ fName +'"/></atom:entry>';
                        
                try{
                 ProvisioningService service = new ProvisioningService();
                 service.useClientLogin('geo@myafza.ae', 'CCPa$$w0rd'); 
                 service.insertEntryXML(atom ); 
                
                Integer statusResponse = service.response.getStatusCode();
                String bodyStatusResponse = service.response.getBody();
                    if(statusResponse == 201 || statusResponse == 200) {//Success and OK
                        system.debug('User Created');
                        //update database     
                        getMyName.Authorized_Manager_s_Name__c = fName + ' ' + lName;              
                        getMyName.isRandomPasswordGenerated__c = true;
                        getMyName.isGoogleProvisioned__c = true;
                        getMyName.Authorize_Managers_Mobile_No__c = mob;
                        
                        //updateAccntList.add(getMyName);
                        update getMyName;
                        System.debug('Success');
                        //sendMailAlert(service.response.getStatus(), getMyName.Name);
                        return 'Success';    
                    }else {
                        system.debug('There was a problem creating the user: status code ' + statusResponse);
                        sendMailAlert(statusResponse, bodyStatusResponse, getMyName.Name);
                        return 'Error : ' + statusResponse + ' => ' + bodyStatusResponse;
                    }
        
                }
                catch(System.Exception err)
                {
                    System.debug('Error : '+ err.getMessage());
                    sendMailAlert(101, err.getMessage(), getMyName.Name);
                    return 'Error : '+ err.getMessage();
                    
                    
                }
                
        
            }
        
        
        return 'Success';
    
    }
       


}